package com.flyan.game.motafx.component;

import cn.hutool.json.JSONObject;
import com.almasb.fxgl.entity.component.Component;
import com.flyan.game.motafx.core.consts.PropertyConsts;
import com.flyan.game.motafx.core.panel.GameInfoPanel;
import com.flyan.game.motafx.core.pojo.LifePanel;
import lombok.Getter;

/**
 * 生命面板组件
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/9
 */
public class LifePanelComponent extends Component {

    /**
     * 生命面板
     */
    @Getter
    private LifePanel lifePanel;

    @Override
    public void onAdded() {
        /* 从实体属性中获取生面板并初始化 */
        JSONObject info = entity.getObject(PropertyConsts.ENTITY_INFO);
        lifePanel = info.getByPath(PropertyConsts.LIFE_PANEL, LifePanel.class);
    }

    public LifePanelComponent setLifePanel(LifePanel lifePanel) {
        if (!lifePanel.equals(this.lifePanel)) {
            this.lifePanel = lifePanel;
            this.update();
        }
        return this;
    }

    /**
     * 更新面板属性到实体
     */
    public void update() {
        if (entity != null) {
            JSONObject info = entity.getObject(PropertyConsts.ENTITY_INFO);
            info.putByPath(PropertyConsts.LIFE_PANEL, lifePanel);
            GameInfoPanel.redraw();
        }
    }

}
